const baseUrl = 'http://192.168.1.225:9080/';
const hash = key => {
    let hash = 0;
    for (var i = 0; i < key.length; i++) {
        hash = (1313 * hash + key.charCodeAt(i)) % 10000000000;
    }
    return hash;
};

const verifyParams= () => {
    let param = {},
        _sid = localStorage.getItem("_sid");
    if (_sid == undefined) {
        _sid = "WS" + new Date().getTime();
        localStorage.setItem("_sid", _sid);
    } else {
        let serverKey = localStorage.getItem("_serverKey");
        if (serverKey==undefined) {
            serverKey = "";
        }
        param._t = new Date().getTime() + "";
        const value = `${_sid}&${serverKey}&${param._t}`;
        param._sign = hash(value);
    }
    param._sid = _sid;

    return param;
};

const fetchData = (url, param, cb) => {
    let params = Object.assign(verifyParams(), param)
    let formData = new FormData();
    console.log(params)
    Object.keys(params).map(key => {
        formData.append(key, params[key])
    });
    (async () => {
        try{
            let res = await fetch(baseUrl+url, { 
                method: 'POST', 
                // headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, 
                body: formData
            }),
                data = await res.json(); // 接口返回数据;可以尝试不加await是什么情况; 这里是直接返回数据比较好还是直接操作数据？
            cb(data)
            if(data.code === 200){
                // cb(data)
            }else if (data.code == 401) {
                // 会话异常; TODO: 该情况下最好跳转到进入登录页或者首页
                localStorage.removeItem("_sid");
                localStorage.removeItem("_serverKey");
            } else if (data.code == 402) {
                // location.href= base.localhostUrl + 'login.html'; // TODO: 需要用户登录，强制跳转到登录页面，或者弹出一个带进入登录页面链接的提示框
            } else if(data.code && data.code !== 200){ 
                var msg = data.msg? data.msg : "服务端处理异常"
                alert(msg) // 提示异常信息
            }
        }catch(e){
            console.log(e)
        }
    })()
}

/**
 * 创建表格
 * @param obj <Object>
 * @param obj.elem <String>,required
 * @param obj.url <String>,required
 * @param obj.where <Object>
 * @param obj.cols <Array>如[[]],required
 * 其他参数参考: http://www.layui.com/doc/modules/table.html#options
 */
const tableOpt = (obj) => {
    if(!obj.data instanceof Array) alert('表格数据必须为数组')
    const baseOpt = {
        method: 'post',
        page: true, // 开启分页
        response: {
            statusName: 'recordsFiltered', //数据状态的字段名称，默认：code
            statusCode: 35, //成功的状态码，默认：0
            // msgName: 'msg', //状态信息的字段名称，默认：msg
            countName: 'recordsTotal', //数据总数的字段名称，默认：count
            dataName: 'data', //数据列表的字段名称，默认：data
        },
    }
    obj.url = baseUrl + obj.url
    obj.where = obj.where? Object.assign(verifyParams(), obj.where): verifyParams()
    let opt = Object.assign(baseOpt, obj)
    return opt
}

export { fetchData, verifyParams, tableOpt}